/**
 * 地址搜索选择页面
 * 支持搜索地址、获取当前位置、地图选点
 */

const { LocationHelper, MapSelector } = require('../../utils/location-helper');

interface LocationInfo {
  name: string;
  address: string;
  latitude: number;
  longitude: number;
  province?: string;
  city?: string;
  district?: string;
}

interface PageData {
  statusBarHeight: number;
  searchKeyword: string;
  searchResults: LocationInfo[];
  currentLocation: LocationInfo;
  loading: boolean;
  loadingText: string;
  showEmpty: boolean;
  emptyText: string;
  showRetry: boolean;
}

Page<PageData, {}>({
  data: {
    statusBarHeight: 0,
    searchKeyword: '',
    searchResults: [],
    currentLocation: {} as LocationInfo,
    loading: false,
    loadingText: '正在搜索...',
    showEmpty: false,
    emptyText: '输入地址关键词进行搜索',
    showRetry: false
  },

  onLoad(options: any) {
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight
    });

    // 自动获取当前位置
    this.getCurrentLocation();
  },

  /**
   * 搜索输入处理
   */
  onSearchInput(e: any) {
    const value = e.detail.value;
    this.setData({
      searchKeyword: value
    });

    // 实时搜索（防抖）
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
    
    if (value.trim()) {
      this.searchTimer = setTimeout(() => {
        this.searchAddress();
      }, 800);
    } else {
      this.setData({
        searchResults: [],
        showEmpty: false
      });
    }
  },

  /**
   * 搜索地址
   */
  async searchAddress() {
    const keyword = this.data.searchKeyword.trim();
    if (!keyword) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      });
      return;
    }

    this.setData({
      loading: true,
      loadingText: '正在搜索地址...',
      showEmpty: false
    });

    try {
      // 使用当前位置作为搜索中心（如果有的话）
      let region = '全国';
      if (this.data.currentLocation.city) {
        region = this.data.currentLocation.city;
      }

      const results = await LocationHelper.searchLocation(keyword, region);
      
      // 如果有当前位置，计算距离
      if (this.data.currentLocation.latitude && this.data.currentLocation.longitude) {
        results.forEach(result => {
          const distance = LocationHelper.calculateDistance(
            this.data.currentLocation.latitude,
            this.data.currentLocation.longitude,
            result.latitude,
            result.longitude
          );
          (result as any).distance = this.formatDistance(distance);
        });
      }

      this.setData({
        searchResults: results,
        loading: false,
        showEmpty: results.length === 0,
        emptyText: '未找到相关地址，请尝试其他关键词'
      });

    } catch (error) {
      console.error('搜索地址失败:', error);
      
      this.setData({
        loading: false,
        showEmpty: true,
        emptyText: error instanceof Error ? error.message : '搜索失败，请重试',
        showRetry: true
      });
    }
  },

  /**
   * 获取当前位置
   */
  async getCurrentLocation() {
    this.setData({
      loading: true,
      loadingText: '正在获取当前位置...'
    });

    try {
      const location = await LocationHelper.getCurrentLocation(true);
      
      this.setData({
        currentLocation: location,
        loading: false
      });

      console.log('当前位置获取成功:', location);

    } catch (error) {
      console.error('获取当前位置失败:', error);
      
      this.setData({
        loading: false,
        showEmpty: !this.data.searchResults.length,
        emptyText: '无法获取当前位置，请手动搜索地址',
        showRetry: true
      });
    }
  },

  /**
   * 打开地图选择器
   */
  async openMapSelector() {
    try {
      const currentLocation = this.data.currentLocation.latitude ? this.data.currentLocation : undefined;
      const selectedLocation = await MapSelector.chooseLocationWithConfirm(currentLocation);
      
      // 返回选择的位置
      this.returnSelectedLocation(selectedLocation);
      
    } catch (error) {
      if (error instanceof Error && !error.message.includes('取消')) {
        wx.showToast({
          title: error.message,
          icon: 'none'
        });
      }
    }
  },

  /**
   * 选择搜索结果中的位置
   */
  selectLocation(e: any) {
    const index = e.currentTarget.dataset.index;
    const selectedLocation = this.data.searchResults[index];
    
    if (selectedLocation) {
      // 显示确认对话框
      wx.showModal({
        title: '确认选择',
        content: `${selectedLocation.name}\n${selectedLocation.address}`,
        confirmText: '确认',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.returnSelectedLocation(selectedLocation);
          }
        }
      });
    }
  },

  /**
   * 选择当前位置
   */
  selectCurrentLocation() {
    if (!this.data.currentLocation.address) {
      wx.showToast({
        title: '当前位置信息不完整',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '确认使用当前位置',
      content: `${this.data.currentLocation.name}\n${this.data.currentLocation.address}`,
      confirmText: '确认',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.returnSelectedLocation(this.data.currentLocation);
        }
      }
    });
  },

  /**
   * 返回选择的位置
   */
  returnSelectedLocation(location: LocationInfo) {
    // 获取上一页面实例
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2];
    
    if (prevPage) {
      // 调用上一页面的回调方法
      if (typeof prevPage.onLocationSelected === 'function') {
        prevPage.onLocationSelected(location);
      }
    }

    // 返回上一页
    wx.navigateBack();
  },

  /**
   * 格式化距离显示
   */
  formatDistance(distance: number): string {
    if (distance < 1000) {
      return `${Math.round(distance)}m`;
    } else {
      return `${(distance / 1000).toFixed(1)}km`;
    }
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack();
  },

  // 搜索防抖定时器
  searchTimer: null as any,

  onUnload() {
    // 清理定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
  }
});
